/**
 * 物料BOM - 新增或编辑界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0001.Goods.GoodsBOMEditForm", {
  extend: "PSI.AFX.Form.EditForm",

  config: {
    goods: null
  },

  /**
   * 初始化组件
   * 
   * @override
   */
  initComponent() {
    const me = this;

    const goods = me.getGoods();

    const entity = me.getEntity();

    me.adding = entity == null;

    let btn = null;

    const buttons = [];
    if (!entity) {
      btn = {
        text: "保存并继续新建",
        ...PSI.Const.BTN_STYLE,
        formBind: true,
        handler() {
          me._onOK(true);
        },
        scope: me
      };

      buttons.push(btn);
    }

    btn = {
      text: "保存",
      ...PSI.Const.BTN_STYLE,
      formBind: true,
      iconCls: "PSI-button-ok",
      handler() {
        me._onOK(false);
      },
      scope: me
    };
    buttons.push(btn);

    btn = {
      text: entity == null ? "关闭" : "取消",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.close();
      },
      scope: me
    };
    buttons.push(btn);

    const t = entity == null ? "新建子件" : "编辑子件";
    const logoHtml = me.genLogoHtml(entity, t);

    const width1 = 600;
    const width2 = 295;
    PCL.apply(me, {
      header: {
        title: me.formatTitle(PSI.Const.PROD_NAME),
        height: 40
      },
      width: 650,
      height: 460,
      layout: "border",
      listeners: {
        show: {
          fn: me._onWndShow,
          scope: me
        },
        close: {
          fn: me._onWndClose,
          scope: me
        }
      },
      items: [{
        region: "north",
        border: 0,
        height: 70,
        html: logoHtml
      }, {
        region: "center",
        border: 0,
        id: me.buildId(me, "editForm"),
        xtype: "form",
        layout: {
          type: "table",
          columns: 2,
          tableAttrs: PSI.Const.TABLE_LAYOUT,
        },
        height: "100%",
        bodyPadding: 5,
        defaultType: 'textfield',
        fieldDefaults: {
          labelAlign: "right",
          labelSeparator: "",
          msgTarget: 'side',
          margin: "5",
          labelWidth: 85,
        },
        items: [{
          xtype: "hidden",
          name: "id",
          value: goods.get("id")
        }, {
          fieldLabel: "母  件",
          width1: width1,
          colspan: 2,
          xtype: "displayfield",
          value: me.toFieldNoteText(`${goods.get("code")} - ${goods.get("name")} ${goods.get("spec")}`)
        }, {
          fieldLabel: "母件单位",
          readOnly: true,
          colspan: 2,
          value: goods.get("unitName"),
          width: width2
        }, {
          id: me.buildId(me, "editSubGoodsCode"),
          fieldLabel: "子件编码",
          width: width1,
          colspan: 2,
          allowBlank: false,
          blankText: "没有输入子件编码",
          beforeLabelTextTpl: entity == null
            ? PSI.Const.REQUIRED
            : "",
          xtype: "psi_subgoodsfield",
          parentCmp: me,
          parentGoodsId: me.goods.get("id"),
          callbackFunc: me._setGoodsInfo,
          callbackFuncScope: me,
          listeners: {
            specialkey: {
              fn: me._onEditCodeSpecialKey,
              scope: me
            }
          }
        }, {
          fieldLabel: "子件品名",
          width: width1,
          readOnly: true,
          colspan: 2,
          id: me.buildId(me, "editSubGoodsName")
        }, {
          fieldLabel: "子件规格型号",
          readOnly: true,
          width: width1,
          colspan: 2,
          id: me.buildId(me, "editSubGoodsSpec")
        }, {
          id: me.buildId(me, "editSubGoodsCount"),
          xtype: "numberfield",
          fieldLabel: "子件数量",
          allowDecimals: PSI.Const.GC_DEC_NUMBER > 0,
          decimalPrecision: PSI.Const.GC_DEC_NUMBER,
          minValue: 0,
          hideTrigger: true,
          name: "subGoodsCount",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          listeners: {
            specialkey: {
              fn: me._onEditCountSpecialKey,
              scope: me
            }
          },
          width: width2,
        }, {
          fieldLabel: "子件单位",
          width: width2,
          readOnly: true,
          id: me.buildId(me, "editSubGoodsUnitName")
        }, {
          id: me.buildId(me, "editCostWeight"),
          xtype: "numberfield",
          fieldLabel: "成本分摊权重",
          labelWidth: 100,
          allowDecimals: false,
          decimalPrecision: 0,
          minValue: 0,
          maxValue: 100,
          hideTrigger: true,
          name: "costWeight",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          value: 1,
          listeners: {
            specialkey: {
              fn: me._onEditCostWeightSpecialKey,
              scope: me
            }
          },
          width: width2,
        }, {
          text: "成本分摊权重的使用帮助",
          ...PSI.Const.BTN_STYLE,
          xtype: "button",
          iconCls: "PSI-tb-help",
          handler() {
            const url = me.URL("/Home/Help/index?t=costWeight")
            window.open(url);
          }
        }, {
          xtype: "hidden",
          id: me.buildId(me, "editSubGoodsId"),
          name: "subGoodsId"
        }, {
          xtype: "hidden",
          name: "addBOM",
          value: entity == null ? "1" : "0"
        }],
        buttons: buttons
      }]
    });

    me.callParent(arguments);

    me.editForm = PCL.getCmp(me.buildId(me, "editForm"));

    me.editSubGoodsCode = PCL.getCmp(me.buildId(me, "editSubGoodsCode"));
    me.editSubGoodsName = PCL.getCmp(me.buildId(me, "editSubGoodsName"));
    me.editSubGoodsCount = PCL.getCmp(me.buildId(me, "editSubGoodsCount"));
    me.editSubGoodsId = PCL.getCmp(me.buildId(me, "editSubGoodsId"));
    me.editSubGoodsSpec = PCL.getCmp(me.buildId(me, "editSubGoodsSpec"));
    me.editSubGoodsUnitName = PCL.getCmp(me.buildId(me, "editSubGoodsUnitName"));
    me.editCostWeight = PCL.getCmp(me.buildId(me, "editCostWeight"));
  },

  /**
   * @private
   */
  _onOK(thenAdd) {
    const me = this;
    const f = me.editForm;
    const el = f.getEl();
    el?.mask(PSI.Const.SAVING);
    const sf = {
      url: me.URL("SLN0001/Goods/editGoodsBOM"),
      method: "POST",
      success(form, action) {
        me.__lastId = action.result.id;

        el?.unmask();

        me.tip("数据保存成功", !thenAdd);
        me.focus();
        if (thenAdd) {
          me.clearEdit();
        } else {
          me.close();
        }
      },
      failure(form, action) {
        el.unmask();
        me.showInfo(action.result.msg, () => {
          me.editSubGoodsCode.focus();
        });
      }
    };
    f.submit(sf);
  },

  /**
   * @private
   */
  _onEditCodeSpecialKey(field, e) {
    const me = this;

    if (e.getKey() == e.ENTER) {
      me.setFocusAndCursorPosToLast(me.editSubGoodsCount);
    }
  },

  /**
   * @private
   */
  _onEditCountSpecialKey(field, e) {
    const me = this;

    if (e.getKey() == e.ENTER) {
      me.setFocusAndCursorPosToLast(me.editCostWeight);
    }
  },

  /**
   * @private
   */
  _onEditCostWeightSpecialKey(field, e) {
    const me = this;

    if (e.getKey() == e.ENTER) {
      const f = me.editForm;
      if (f.getForm().isValid()) {
        me._onOK(me.adding);
      }
    }
  },

  /**
   * @private
   */
  clearEdit() {
    const me = this;

    me.editSubGoodsCode.focus();

    const editors = [me.editSubGoodsId, me.editSubGoodsCode,
    me.editSubGoodsName, me.editSubGoodsSpec, me.editSubGoodsCount,
    me.editSubGoodsUnitName];
    for (let i = 0; i < editors.length; i++) {
      const edit = editors[i];
      edit.setValue(null);
      edit.clearInvalid();
    }
  },

  /**
   * @private
   */
  _onWndClose() {
    const me = this;

    const parentForm = me.getParentForm();
    if (parentForm) {
      parentForm._keyMapMain.enable();
    }

    // AFX
    PCL.get(window).un('beforeunload', me.__onWindowBeforeUnload);

    if (me.getParentForm()) {
      me.getParentForm().refreshGoodsBOM.apply(me.getParentForm());
    }
  },

  /**
   * @private
   */
  _onWndShow() {
    const me = this;

    const parentForm = me.getParentForm();
    if (parentForm) {
      parentForm._keyMapMain.disable();
    }

    // AFX
    PCL.get(window).on('beforeunload', me.__onWindowBeforeUnload);

    const subGoods = me.getEntity();
    if (!subGoods) {
      // 新增子商品

      me.setFocusAndCursorPosToLast(me.editSubGoodsCode);
      return;
    }

    // 编辑子商品
    const r = {
      url: me.URL("SLN0001/Goods/getSubGoodsInfo"),
      params: {
        goodsId: me.getGoods().get("id"),
        subGoodsId: subGoods.get("goodsId")
      },
      callback(options, success, response) {
        if (success) {
          const data = me.decodeJSON(response.responseText);
          if (data.success) {
            me.editSubGoodsCode.setValue(data.code);
            me.editSubGoodsName.setValue(data.name);
            me.editSubGoodsSpec.setValue(data.spec);
            me.editSubGoodsUnitName.setValue(data.unitName);
            me.editSubGoodsCount.setValue(data.count);
            me.editCostWeight.setValue(data.costWeight);

            me.editSubGoodsId.setValue(subGoods.get("goodsId"));

            me.editSubGoodsCode.setReadOnly(true);
            me.editSubGoodsCount.focus();
          } else {
            me.showInfo(data.msg);
          }
        } else {
          me.showInfo("网络错误");
        }
      }
    };
    me.ajax(r);
  },

  /**
   * @private
   */
  _setGoodsInfo(goods) {
    const me = this;
    if (goods) {
      me.editSubGoodsId.setValue(goods.get("id"));
      me.editSubGoodsName.setValue(goods.get("name"));
      me.editSubGoodsSpec.setValue(goods.get("spec"));
      me.editSubGoodsUnitName.setValue(goods.get("unitName"));
    } else {
      me.editSubGoodsId.setValue(null);
      me.editSubGoodsName.setValue(null);
      me.editSubGoodsSpec.setValue(null);
      me.editSubGoodsUnitName.setValue(null);
    }
  }
});
